package com.xneure.code.log;

import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSessionEvent;
import com.xneure.code.AutoProxy;
import com.xneure.code.msg.MsgManage;
import com.xneure.utils.ObjectUtil;
import com.xneure.utils.SpringUtil;
import com.xneure.utils.bean.BeanProcessor;
import com.xneure.utils.formatfile.inifile.IniFileObject;
import com.xneure.utils.formatfile.inifile.IniFileParse;
import com.xneure.utils.formatfile.inifile.IniSection;
import com.xneure.utils.formatfile.inifile.IniValue;
import com.xneure.utils.intf.SessionChangeEvent;
import com.xneure.utils.intf.SystemListener;

public class LogLoad implements SystemListener{
	@Override
	public void stop(ServletContextEvent sce){
		LogManage.saveAllLog();
		LogManage.reset();
	}

	@Override
	public void start(ServletContextEvent sce){
		MsgManage.getSysMsgManage().sendMessage(new AutoProxy("com.xneure"));
		String cfg = sce.getServletContext().getInitParameter("iLogConfig");
		if(null != cfg){
			IniFileObject ifo = IniFileParse.parse(cfg);
			if(null == ifo){
				LogManage.monitorSystemOut();
				LogManage.registerWatcher(new DefaultHandle());
			}else{
				IniSection section = ifo.getSection("DefConfig");
				if(null != section){
					DefaultHandle lw;
					String vl = section.getValue("DefClass");
					if(null != vl && vl.length() > 1){
						lw = ObjectUtil.newInstance(vl);
						if("true".equals(section.getValue("SysOut"))){
							LogManage.monitorSystemOut();
						}
					}else{
						lw = new DefaultHandle();
						LogManage.monitorSystemOut();
					}
					BeanProcessor om = new BeanProcessor(lw);
					for(IniValue obj:section.getValues()){
						String key = obj.getKey();
						if(key.equalsIgnoreCase("DefConfig") || key.equalsIgnoreCase("DefClass") || key.equalsIgnoreCase("SysOut")){
							continue;
						}
						om.setValue(key,obj.getValue());
					}
					LogManage.registerWatcher(lw);
				}
			}
		}else{
			LogManage.monitorSystemOut();
			LogManage.registerWatcher(new DefaultHandle());
		}
	}

	@Override
	public void sessionCreated(HttpSessionEvent se){
		String[] sces = SpringUtil.getBeanName(SessionChangeEvent.class);
		if(ObjectUtil.isNotNull(sces)){
			for(String sce:sces){
				((SessionChangeEvent)SpringUtil.getBean(sce)).create(se.getSession());
			}
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se){
		String[] sces = SpringUtil.getBeanName(SessionChangeEvent.class);
		if(ObjectUtil.isNotNull(sces)){
			for(String sce:sces){
				((SessionChangeEvent)SpringUtil.getBean(sce)).destroy(se.getSession());
			}
		}
	}
}
